package com.tangr.normaladapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by tangr on 2016/6/7.
 */
public class ViewHolder extends RecyclerView.ViewHolder {
    private SparseArray<View> mViews;
    private int mLayoutId;
    private View mConvertView;

    public ViewHolder(View itemView,int layoutId) {
        super(itemView);
        this.mViews = new SparseArray<View>();
        mConvertView = itemView;
        mLayoutId = layoutId;
        mConvertView.setTag(this);
    }

    public static ViewHolder get(Context context,View convertView,ViewGroup parent,int layoutId){
        if(convertView==null){
            View itemView = LayoutInflater.from(context).inflate(layoutId, parent,
                    false);
            return new ViewHolder(itemView,layoutId);
        }
        return (ViewHolder) convertView.getTag();
    }

    public <T extends View> T getView(int viewId){
        View v = mViews.get(viewId);
        if (v == null){
            v = mConvertView.findViewById(viewId);
            mViews.put(viewId,v);
        }
        return (T) v;
    }

    public View getConvertView(){
        return mConvertView;
    }

    public void setText(int viewId,String text){
        TextView tv = (TextView) mConvertView.findViewById(viewId);
        tv.setText(text);
    }

    public void setImage(int viewId,int resId){
        ImageView iv = (ImageView) mConvertView.findViewById(viewId);
        iv.setImageResource(resId);
    }

    public int getLayoutId(){
        return mLayoutId;
    }
}
